package me.grm.cs.database;

import me.grm.cs.course.CourseInfo;
import me.grm.cs.course.ICourse;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class TextDatabase implements IDatabase {
    private static final IDatabase database;
    private static final ArrayList<CourseInfo> Courses;

    static {
        database = new TextDatabase();
        Courses = new ArrayList<CourseInfo>();

        String configFile = "F:\\workspace\\javaespresso\\courseSelection\\src\\main\\resources\\config";
        System.out.printf("Looking for configuration file %s\n", configFile);
        // 获取类名（公选课、专业课）
        // 从配置文件中读取课程信息
        try (FileInputStream stream = new FileInputStream(configFile)) {
            Scanner sc = new Scanner(stream);
            String className = "";
            while(sc.hasNextLine()) {
                String line  = sc.nextLine();
                if(line.startsWith("!")) {
                    className = line.substring(1);
                }
                else if(line.equals("")){
                    continue;
                }
                else {
                    String id = line;
                    String name = sc.nextLine();
                    Courses.add(new CourseInfo(id, name, className));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private TextDatabase() {}

    public static IDatabase getInstance() {
        return database;
    }

    @Override
    public String getCourseName(int index) {
        return Courses.get(index).name;
    }

    @Override
    public CourseInfo getCourseInfo(int index) {
        return Courses.get(index);
    }

    @Override
    public void listCourses() {
        for(CourseInfo ci : Courses ) {
            System.out.println(ci);
        }
    }
}
